package com.slb.slnwp.common.exception;

import com.slb.slnwp.common.utils.ResponseJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.UndeclaredThrowableException;
import java.util.Objects;

/**
 * @author : joinly
 * @c创建时间: 2021-10-10 17:36:44
 * @描述: 全局异常处理类
 **/
@Slf4j
@ControllerAdvice
public class GlobalException {

    /**
     * 异常处理方法，根据不同类型的异常返回不同的ResponseJson对象
     * 对异常进行分类，分类识别，分类处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseJson handle(Throwable e) {
        // BizException类型异常的处理
        if (e instanceof BizException) {
            BizException ex = (BizException) e;
            return new ResponseJson(ex.getCode(), e.getMessage(), ex.getData());
        }
        /*if (e instanceof ValidateException) {
            ValidateException ex = (ValidateException) e;
            return new ResponseJson(HttpStatus.HTTP_INTERNAL_ERROR, ex.getMessage());
        }*/
        // 方法参数验证失败异常MethodArgumentNotValidException的处理
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            return new ResponseJson(500, Objects.requireNonNull(ex.getBindingResult().getFieldError()).getDefaultMessage());
        }
        // BindException类型异常的处理
        if (e instanceof BindException) {
            FieldError fieldError = ((BindException) e).getBindingResult().getFieldError();
            String msg = "参数错误";
            if (fieldError != null && fieldError.getDefaultMessage() != null) {
                msg = fieldError.getDefaultMessage();
            }
            return new ResponseJson(500, msg);
        }
        if (e instanceof UndeclaredThrowableException) {
            e = ((UndeclaredThrowableException) e).getUndeclaredThrowable();
        }
        log.error("系统异常", e);
        return ResponseJson.fail();
    }
}
